//
//  AddDeviceListView.swift
//  casdon_swiftUI
//
//  Created by casdon on 2025/5/20.
//

import SwiftUI
import FlowStacks
import SDWebImageSwiftUI
struct Device: Identifiable {
    let id: Int
    let name: String
    let imageUrl: String
}
struct AddDeviceListView: View {
    @StateObject private var viewModel: AddDeviceListViewModel
    @EnvironmentObject var navigator: FlowNavigator<HomeStack>
    
    let devices = [
        Device(id: 1, name: "蒸烤箱TD Pro三代", imageUrl: "https://images.tuyacn.com/smart/icon/bay1724726183769h1YG/1731987857e8bee29e041.png"),
        Device(id: 2, name: "智能冰箱X1", imageUrl: "https://images.tuyacn.com/smart/icon/bay1724726183769h1YG/1731987857e8bee29e041.png"),
        Device(id: 3, name: "空气净化器Pro", imageUrl: "https://images.tuyacn.com/smart/icon/bay1724726183769h1YG/1731987857e8bee29e041.png"),
        Device(id: 4, name: "扫地机器人S3", imageUrl: "https://images.tuyacn.com/smart/icon/bay1724726183769h1YG/1731987857e8bee29e041.png"),
        Device(id: 5, name: "智能空调Cool", imageUrl: "https://images.tuyacn.com/smart/icon/bay1724726183769h1YG/1731987857e8bee29e041.png")
    ]
    
    init(viewModel: AddDeviceListViewModel) {
        _viewModel = StateObject(wrappedValue: viewModel)
    }
    var body: some View {
        ZStack{
            AppColors.Gray1
         
            VStack(alignment: .leading){
                NavigationBar(title: "添加设备")
                HStack{
                    Text("搜索附近设备已暂停")
                        .padding(.leading, 24)
                        .font(.system(size: 14, weight: .regular))
                        .foregroundColor(AppColors.Gy2)
                    Button("重新搜索"){
                        //TODO: 重新搜索
                    }
                    .padding(.leading, 5)
                    .font(.system(size: 14, weight: .regular))
                    .foregroundColor(AppColors.Brand6)
                }.padding(.top, 12)
                ScrollView {
                    LazyVStack(spacing: 12) {
                        ForEach(viewModel.peripheralIDs, id: \.self) { id in
                            DeviceItemView(id: id, viewModel: viewModel)
                                      .padding(.horizontal, 16)
                              }
                          }
                          .padding(.top, 12)
                }
            }
        
            Spacer()
        }.onChange(of: viewModel.showWifiInfoPage, perform: { result in
            if result {
                navigator.presentSheet(.wifiInfo)
                viewModel.showWifiInfoPage = false
            }
        })
        
    }
}

enum DeviceButtonState {
    case notStarted
    case inProgress
    case completed
}

struct DeviceItemView: View {
    let id: UUID
    let peripheral:Peripheral?
    @StateObject private var viewModel: AddDeviceListViewModel
    @State private var buttonState: DeviceButtonState = .notStarted
    
    // 按钮状态枚举
    enum DeviceButtonState {
        case notStarted    // 未开始（渐变按钮）
        case inProgress    // 进行中（加载动画）
        case completed     // 已完成（白底蓝字）
    }
    
    init(id: UUID, viewModel: AddDeviceListViewModel) {
        _viewModel = StateObject(wrappedValue: viewModel)
        self.id = id
        self.peripheral = viewModel.periPheralWithID(id)
    }
    
    var body: some View {
        HStack(spacing: 12) {
            // 设备图标
            WebImage(url: URL(string: self.peripheral?.cover ?? ""))
                .resizable()
                .scaledToFit()
                .frame(width: 40, height: 40)
            
            // 设备名称
            Text(self.peripheral?.name ?? "")
                .font(.system(size: 14))
                .foregroundColor(AppColors.Gy1)
            
            Spacer()
            
            // 动态按钮（根据状态变化）
            buttonContent
                .frame(width: 80, height: 32) // 固定按钮尺寸
                .contentShape(Rectangle())
        }
        .padding(12)
        .background(Color.white)
        .cornerRadius(8)
        .shadow(color: Color.black.opacity(0.05), radius: 4, y: 2)
    }
    
    // MARK: - 按钮内容（根据状态动态显示）
    @ViewBuilder private var buttonContent: some View {
        switch buttonState {
        case .notStarted:
            Button(action: startDeviceSetup) {
                Text("开始")
            }
            .buttonStyle(GradientButtonStyle())
            
        case .inProgress:
            Button(action: {}) {
                ProgressView()
                    .progressViewStyle(CircularProgressViewStyle(tint: .white))
                    .frame(maxWidth: .infinity, maxHeight: .infinity)
            }
            .buttonStyle(GradientButtonStyle())
            .disabled(true)
            
        case .completed:
            Button(action: renameDevice) {
                Text("修改名称")
            }
            .buttonStyle(CompletedButtonStyle())
        }
    }
    
    // MARK: - 按钮点击事件
    private func startDeviceSetup() {
    //    buttonState = .inProgress
        // 模拟3秒后完成（实际替换为你的网络请求）
//        DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
//            buttonState = .completed
//        }
        viewModel.start(id: self.id)
    }
    
    private func renameDevice() {
        print("修改设备名称")
        // 这里添加修改名称的逻辑
    }
}


// MARK: - 按钮样式定义
struct GradientButtonStyle: ButtonStyle {
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .font(.system(size: 14, weight: .medium))
            .foregroundColor(.white)
            .frame(maxWidth: .infinity, maxHeight: .infinity) // 确保填满父视图
            .background(
                LinearGradient(
                    colors: [Color(hex: "#9470FF"), Color(hex: "#6652F9")],
                    startPoint: .leading,
                    endPoint: .trailing
                )
            )
            .cornerRadius(6)
            .opacity(configuration.isPressed ? 0.8 : 1.0)
            .contentShape(Rectangle()) // 确保整个区域都可点击
    }
}

struct CompletedButtonStyle: ButtonStyle {
    func makeBody(configuration: Configuration) -> some View {
        configuration.label
            .font(.system(size: 14, weight: .medium))
            .foregroundColor(AppColors.Brand6) // 使用你的主蓝色
            .frame(maxWidth: .infinity, maxHeight: .infinity) // 确保填满父视图
            .background(Color.white)
            .cornerRadius(6)
            .contentShape(Rectangle()) // 确保整个区域都可点击
    }
}
